﻿#define TRACE
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using MathHelper;
using System.Diagnostics;
using System.Web.Services.Protocols;

/// <summary>
/// Summary description for SimpleService
/// </summary>
[WebService(Namespace = "http://mydomain.net/", Description = "Service Description", Name = "My Service Name")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class SimpleService : System.Web.Services.WebService
{
    public GetAllInfoHeader MoreInfo { get; set; }

    public SimpleService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod] // Attribute
    public int Mod(int a, int b)
    {
        return DivHelper.Mod(a, b);
    }
    
    [WebMethod]
    [SoapHeader("MoreInfo", Direction = SoapHeaderDirection.InOut)]
    public Product GetProductByPrimaryKey(int productId)
    {
        SqlConnection sqlConnection = new SqlConnection();

        if (MoreInfo == null)
            throw new SoapHeaderException("MoreInfo bị null", SoapHeaderException.ServerFaultCode);

        if (MoreInfo.Flag)
            throw new SoapException("Connection bị null", SoapException.ServerFaultCode);

        sqlConnection.ConnectionString =
            ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;

        // Lấy tất cả Product, trả về dạng DataTable
        sqlConnection.Open();

        DataTable tableProduct = new DataTable();

        SqlCommand sqlCommand = new SqlCommand("usp_Product_GetByPrimaryKey", sqlConnection);
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.Parameters.AddWithValue("@ProductId", productId);
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
        sqlDataAdapter.Fill(tableProduct);

        sqlConnection.Close();

        Product p = new Product();
        if (tableProduct.Rows.Count > 0)
        {
            p.ProductID = (int) tableProduct.Rows[0]["ProductID"];
            p.ProductName = (string) tableProduct.Rows[0]["ProductName"];
        }

        return p;
    }
}
